import sqlite3


def execute(fn, commit=False):
    try:
        conn = sqlite3.connect("enterprise.db")
        curs = conn.cursor()

        fn(curs)
        if commit:
            conn.commit()
    finally:
        if curs:
            curs.close()
        if conn:
            conn.close()


def drop():
    execute(lambda curs: curs.execute("DROP TABLE zoo"))


def create():
    execute(
        lambda curs: curs.execute(
            """
            CREATE TABLE IF NOT EXISTS zoo (
                critter VARCHAR(20) PRIMARY KEY,
                count INT,
                damages FLOAT
            )
            """
        )
    )


def insert():
    def insert_inner(curs):
        curs.execute('INSERT INTO zoo VALUES("duck", 5, 0.0)')
        curs.execute('INSERT INTO zoo VALUES("bear", 2, 1000.0)')

        ins = "INSERT INTO zoo (critter, count, damages) VALUES(?, ?, ?)"
        curs.execute(ins, ("weasel", 1, 2000.0))

    create()
    execute(insert_inner, commit=True)


def query():
    print("query")
    try:
        conn = sqlite3.connect("enterprise.db")
        curs = conn.cursor()

        curs.execute("select * from zoo")
        rows = list(curs.fetchall())
        assert rows == [("duck", 5, 0.0), ("bear", 2, 1000.0), ("weasel", 1, 2000.0)]
    finally:
        if curs:
            curs.close()
        if conn:
            conn.close()


if __name__ == "__main__":
    insert()
